package org.atovio.coolexam.controller.student;

import org.atovio.coolexam.common.Result;
import org.atovio.coolexam.entity.*;
import org.atovio.coolexam.service.*;
import org.atovio.coolexam.viewmodel.student.home.ExamPaperCardVM;
import org.atovio.coolexam.viewmodel.student.home.SubjectCardVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController("StudentHomeController")
@RequestMapping("/student/home")
public class HomeController {

    private final ExamPaperAnswerService examPaperAnswerService;
    private final ExamPaperService examPaperService;
    private final SubjectService subjectService;
    private final UserService userService;

    @Autowired
    public HomeController(ExamPaperService examPaperService, SubjectService subjectService,
                          ExamPaperAnswerService examPaperAnswerService, UserService userService) {
        this.examPaperAnswerService = examPaperAnswerService;
        this.examPaperService = examPaperService;
        this.subjectService = subjectService;
        this.userService = userService;
    }

    @GetMapping("/card/examPapers")
    public Result getExamPaperDetails(@RequestParam Integer userId) {
        List<ExamPaperCardVM> examPaperCardVMS = new ArrayList<>();

        List<ExamPaper> examPapers = examPaperService.getAll();
        examPapers.forEach(e -> {
            ExamPaperCardVM vm = new ExamPaperCardVM();
            List<ExamPaperAnswer> epa = examPaperAnswerService.getBySelective(
                    Map.of("examPaperId", e.getId(), "createUserId", userId));
            vm.setExamPaper(e);
            vm.setExamPaperAnswer(!epa.isEmpty()
                    ? epa.get(0) : null);
            examPaperCardVMS.add(vm);
        });
        return Result.success(examPaperCardVMS);
    }

    @GetMapping("/card/subjects")
    public Result getSubjectDetails() {
        List<SubjectCardVM> scData = new ArrayList<>();

        List<Subject> subjects = subjectService.getAllSubject();
        subjects.forEach(s -> {
            SubjectCardVM scVM = new SubjectCardVM();
            Subject su = subjectService.getById(s.getId());
            User user = userService.getByUserId(su.getTUserId());

            scVM.setUser(user);
            scVM.setSubject(su);

            scData.add(scVM);
        });

        return Result.success(scData);
    }
}
